/**
 * 快速启动应用模块
 * 负责管理和启动常用应用程序
 */

const { ipcRenderer } = require('electron');
const config = require('../../main/utils/config').quickApps;
const { handleError, ErrorTypes, tryCatch } = require('../../common/error-handler');
const { showToast } = require('../../common/show-toast');



const launcherPanel = document.getElementById('launcher-panel');
const launcherList = document.getElementById('launcher-list');
const btnAddApp = document.getElementById('btn-add-app');
let launcherApps = JSON.parse(localStorage.getItem('launcherApps') || '[]');
/**
 * 初始化快速启动应用模块
 */
function initialize() {
    console.log('初始化快速启动应用模块...');
    // 初始化
    renderLauncher();
    launcherPanel.style.display = '';


    console.log('快速启动应用模块初始化完成');
}

// 渲染启动器
function renderLauncher() {
    launcherList.innerHTML = '';
    launcherApps.forEach((app, index) => {
        const appItem = document.createElement('div');
        appItem.className = 'app-item';

        // 根据应用名称确定图标和类别
        const iconInfo = getAppIconInfo(app.name);

        // 创建图标元素
        const iconElement = document.createElement('div');
        iconElement.className = `app-icon ${iconInfo.className}`;
        iconElement.innerHTML = `<i class="${iconInfo.icon}"></i>`;

        // 创建名称元素
        const nameElement = document.createElement('div');
        nameElement.className = 'app-name';
        nameElement.textContent = app.name;
        nameElement.title = app.name;

        // 创建删除按钮
        const deleteBtn = document.createElement('button');
        deleteBtn.className = 'delete-btn';
        deleteBtn.innerHTML = '<i class="fas fa-times"></i>';
        deleteBtn.onclick = (e) => {
            e.stopPropagation();
            if (confirm(`确定要删除 ${app.name} 吗？`)) {
                launcherApps.splice(index, 1);
                saveLauncherApps();
                renderLauncher();
                showToast('应用已删除', 'success');
            }
        };

        // 添加点击事件启动应用
        appItem.onclick = (e) => {
            if (!launcherPanel.classList.contains('edit-mode')) {
                ipcRenderer.send('launch-app', app.path);
            }
        };

        appItem.appendChild(iconElement);
        appItem.appendChild(nameElement);
        appItem.appendChild(deleteBtn);
        launcherList.appendChild(appItem);
    });

    // 更新空状态显示
    const emptyState = document.getElementById('launcher-empty-state');
    if (emptyState) {
        emptyState.style.display = launcherApps.length > 0 ? 'none' : 'flex';
    }
}

// 根据应用名称智能选择图标
function getAppIconInfo(appName) {
    const nameLower = appName.toLowerCase();

    // 浏览器
    if (nameLower.includes('safari')) return { icon: 'fab fa-safari', className: 'app-icon-safari' };
    if (nameLower.includes('chrome')) return { icon: 'fab fa-chrome', className: 'app-icon-chrome' };
    if (nameLower.includes('edge')) return { icon: 'fab fa-edge', className: 'app-icon-edge' };
    if (nameLower.includes('firefox')) return { icon: 'fab fa-firefox', className: 'app-icon-firefox' };
    if (nameLower.includes('browser') || nameLower.includes('浏览器')) return { icon: 'fas fa-globe', className: 'app-icon-edge' };

    // 社交媒体和通讯
    if (nameLower.includes('facetime')) return { icon: 'fas fa-video', className: 'app-icon-video' };
    if (nameLower.includes('mail') || nameLower.includes('邮件')) return { icon: 'fas fa-envelope', className: 'app-icon-mail' };
    if (nameLower.includes('微信') || nameLower.includes('wechat')) return { icon: 'fab fa-weixin', className: 'app-icon-chat' };
    if (nameLower.includes('qq')) return { icon: 'fab fa-qq', className: 'app-icon-chat' };
    if (nameLower.includes('message') || nameLower.includes('信息')) return { icon: 'fas fa-comment', className: 'app-icon-chat' };

    // 办公软件
    if (nameLower.includes('word') || nameLower.includes('文档')) return { icon: 'fas fa-file-word', className: 'app-icon-document' };
    if (nameLower.includes('excel') || nameLower.includes('表格')) return { icon: 'fas fa-file-excel', className: 'app-icon-document' };
    if (nameLower.includes('powerpoint') || nameLower.includes('演示')) return { icon: 'fas fa-file-powerpoint', className: 'app-icon-document' };
    if (nameLower.includes('pdf')) return { icon: 'fas fa-file-pdf', className: 'app-icon-document' };
    if (nameLower.includes('text') || nameLower.includes('文本')) return { icon: 'fas fa-file-alt', className: 'app-icon-document' };
    if (nameLower.includes('note') || nameLower.includes('笔记')) return { icon: 'fas fa-sticky-note', className: 'app-icon-document' };

    // 开发工具
    if (nameLower.includes('code') || nameLower.includes('编辑器') || nameLower.includes('编程'))
        return { icon: 'fas fa-code', className: 'app-icon-code' };
    if (nameLower.includes('terminal') || nameLower.includes('命令') || nameLower.includes('终端'))
        return { icon: 'fas fa-terminal', className: 'app-icon-code' };
    if (nameLower.includes('git') || nameLower.includes('github'))
        return { icon: 'fab fa-github', className: 'app-icon-code' };

    // 多媒体
    if (nameLower.includes('music') || nameLower.includes('音乐') || nameLower.includes('播放器'))
        return { icon: 'fas fa-music', className: 'app-icon-music' };
    if (nameLower.includes('video') || nameLower.includes('视频') || nameLower.includes('影音'))
        return { icon: 'fas fa-film', className: 'app-icon-video' };
    if (nameLower.includes('photo') || nameLower.includes('图片') || nameLower.includes('图像'))
        return { icon: 'fas fa-image', className: 'app-icon-image' };

    // 系统工具
    if (nameLower.includes('folder') || nameLower.includes('访达') || nameLower.includes('文件夹') || nameLower.includes('explorer'))
        return { icon: 'fas fa-folder', className: 'app-icon-document' };
    if (nameLower.includes('setting') || nameLower.includes('设置'))
        return { icon: 'fas fa-cog', className: 'app-icon-code' };

    // 娱乐
    if (nameLower.includes('game') || nameLower.includes('游戏'))
        return { icon: 'fas fa-gamepad', className: 'app-icon-game' };

    // 默认返回一个应用图标
    return { icon: 'fas fa-cube', className: '' };
}

// 编辑模式切换
const btnEditApps = document.getElementById('btn-edit-apps');

btnEditApps.addEventListener('click', () => {
    const isEditMode = launcherPanel.classList.toggle('edit-mode');
    btnEditApps.classList.toggle('active');
    btnEditApps.innerHTML = isEditMode
        ? '<i class="fas fa-check"></i> 完成编辑'
        : '<i class="fas fa-edit"></i> 编辑应用';
    showToast(isEditMode ? '已进入编辑模式' : '已退出编辑模式', 'info');
});



// 右键菜单
function showLauncherMenu(x, y, idx) {
    let menu = document.getElementById('launcher-menu');
    if (menu) menu.remove();
    menu = document.createElement('div');
    menu.className = 'launcher-menu';
    menu.id = 'launcher-menu';

    const rename = document.createElement('div');
    rename.className = 'launcher-menu-item';
    rename.textContent = '重命名';
    rename.onclick = () => {
        const newName = prompt('输入新名称', launcherApps[idx].name);
        if (newName) {
            launcherApps[idx].name = newName;
            saveLauncherApps();
            renderLauncher();
        }
        menu.remove();
    };
    menu.appendChild(rename);

    const remove = document.createElement('div');
    remove.className = 'launcher-menu-item';
    remove.textContent = '删除';
    remove.onclick = () => {
        launcherApps.splice(idx, 1);
        saveLauncherApps();
        renderLauncher();
        menu.remove();
    };
    menu.appendChild(remove);

    menu.style.left = x + 'px';
    menu.style.top = y + 'px';
    document.body.appendChild(menu);

    document.onclick = () => menu.remove();
}

// 显示自定义对话框
function showCustomPrompt(defaultValue = '') {
    return new Promise((resolve, reject) => {
        const modal = document.getElementById('custom-prompt');
        const input = document.getElementById('app-name-input');
        const confirmBtn = document.getElementById('confirm-app-name');
        const cancelBtn = document.getElementById('cancel-app-name');

        input.value = defaultValue;
        modal.style.display = 'flex';
        input.focus();

        function closeModal() {
            modal.style.display = 'none';
            input.value = '';
        }

        function handleConfirm() {
            const value = input.value.trim();
            if (value) {
                resolve(value);
            } else {
                reject(new Error('应用名称不能为空'));
            }
            closeModal();
        }

        function handleCancel() {
            reject(new Error('用户取消'));
            closeModal();
        }

        // 绑定事件
        confirmBtn.onclick = handleConfirm;
        cancelBtn.onclick = handleCancel;

        // 处理回车键
        input.onkeyup = (e) => {
            if (e.key === 'Enter') handleConfirm();
            if (e.key === 'Escape') handleCancel();
        };
    });
}

// 添加应用
btnAddApp.onclick = async () => {
    try {
        const result = await ipcRenderer.invoke('select-app');
        if (result) {
            try {
                const name = await showCustomPrompt(result.name);
                launcherApps.push({
                    name: name,
                    path: result.path,
                    icon: result.icon
                });
                saveLauncherApps();// 保存应用到本地
                renderLauncher();// 刷新应用列表
                showToast('应用添加成功', 'success');
            } catch (error) {
                if (error.message !== '用户取消') {
                    console.log('添加应用失败:', error);
                    showToast(error.message, 'error');
                }
            }
        }
    } catch (error) {
        console.log('选择应用失败:', error);
        showToast('选择应用失败，请重试', 'error');
    }
};

// 保存到本地
function saveLauncherApps() {
    localStorage.setItem('launcherApps', JSON.stringify(launcherApps));

    // 通知主进程更新全局应用列表
    ipcRenderer.send('launcher-apps-update', JSON.stringify(launcherApps));
}

// 导出模块
module.exports = {
    initialize
};